﻿using System.Net.Mail;

namespace TWA.TFS
{
    /// <summary>
    /// A limited directory user focused on display name and email address
    /// </summary>
    internal class User
    {
        internal string DisplayName { get; private set; }

        internal string EmailAddress
        {
            get
            {
                if (MailAddress == null)
                {
                    return string.Empty;
                }

                return MailAddress.Address;
            } 
        }

        private MailAddress mailAddress;

        internal MailAddress MailAddress
        {
            get
            {
                if (mailAddress == null && !string.IsNullOrEmpty (DisplayName))
                {
                    string userEmail = Directory.GetEmailAddress (DisplayName);

                    if (userEmail != null)
                    {
                        mailAddress = new MailAddress (userEmail);
                    }
                }

                return mailAddress;
            }
        }

        internal User (string displayName)
        {
            // If duplicate users exist in AD, TFS returns their name as "First Last (watc\logonName)", 
            // causing the AD email lookup to fail; so remove the " (watc\logonName)" substring.

            int qualifiedLogonNameIndex = displayName.ToLowerInvariant ().IndexOf (" (watc");

            if (qualifiedLogonNameIndex > 0)
            {
                displayName = displayName.Remove (qualifiedLogonNameIndex);
            }

            DisplayName = displayName;
        }
    }
}